package com.yunti.yntk.manager;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.widget.Toast;

import java.util.Locale;

public class TTSManager {
    private static TTSManager instance;
    private Context mContext;
    private TextToSpeech tts;

    private TTSManager() {

    }

    public static TTSManager getInstance() {
        if (instance == null) {
            instance = new TTSManager();
        }

        return instance;
    }

    public void init(Context context) {
        this.mContext = context;
        tts = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = tts.setLanguage(Locale.CHINESE);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Toast.makeText(mContext, "Language not supported", Toast.LENGTH_SHORT).show();
                    } else {
                        // 设置进度监听器（可选）
                        tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                            @Override
                            public void onStart(String utteranceId) {
                                // 开始播放
                            }

                            @Override
                            public void onDone(String utteranceId) {
                                // 播放结束
                            }

                            @Override
                            public void onError(String utteranceId) {
                                // 发生错误
                            }
                        });
                    }
                }
            }
        });
    }

    public void speakText(String text) {
        new Thread(()->{
            if (tts != null) {
                if(tts.isSpeaking()){
                    tts.stop();
                }
                tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
            }
        }).start();
    }
}
